import { fetchUserProfile } from '../services/user';

export default {
  namespace: 'user',

  state: {
    list: [],
    loading: false,
    currentUser: undefined,
    isLogin: false,
  },

  effects: {
    *fetchUserProfile({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(fetchUserProfile, payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
      if (callback) {
        callback();
      }
    },
  },

  reducers: {
    logout(state) {
      return {
        ...state,
        currentUser: undefined,
        isLogin: false,
      };
    },
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    saveCurrentUser(state, { payload }) {
      return {
        ...state,
        isLogin: true,
        currentUser: payload,
      };
    },
    changeNotifyCount(state, { payload }) {
      return {
        ...state,
        notifyCount: payload,
      };
    },
  },
};
